var menugrid; // 树对象
var oTable;// datatable表格对象
var bTable;
var roleid;

// 初始加载角色树
$(function() {

	$('#roleTab a:first').click(function() {
		initMenu(roleid);
	});
	initRole();
});

// 初始化角色列表方法
function initRole(id) {
	var un = $("#ue").val();
	$
			.ajax({
				url : _path + "/role/initRole",
				type : "POST",
				async : false,
				dataType : "json",
				success : function(result) {
					if (result.msg == "success") {
						var array = result.roleList;
						var html = new Array();
						var j = 0;
						for (var i = 0; i < array.length; i++) {
							if (array[i].rolename == "超级管理员") {

								if (un == "superadmin") {

									html.push('<a id="' + array[i].id
											+ '" href="javascript:show(\''
											+ array[i].id
											+ '\')" class="list-group-item">');
									html
											.push('<i class="fa '
													+ (array[i].isactive === '0' ? 'fa-frown-o'
															: 'fa-home')
													+ '"></i>&nbsp;'
													+ array[i].rolename);
									html
											.push('<div class="btn-group btn-group-xs" style="float: right">');
									html
											.push('<button type="button" class="btn btn-warning" onclick="editRole(\''
													+ array[i].id
													+ '\',\''
													+ array[i].rolename
													+ '\',\''
													+ array[i].isactive
													+ '\',\''
													+ array[i].roledesc
													+ '\')"><i class="fa fa-cog"></i></button>');
									html
											.push('&nbsp;<button type="button" class="btn btn-danger" onclick="delRole(\''
													+ array[i].id
													+ '\',\''
													+ array[i].rolename
													+ '\')"><i class="fa fa-trash-o"></i></button>');
									html.push('</div></a>');

								}
							} else {
								html.push('<a id="' + array[i].id
										+ '" href="javascript:show(\''
										+ array[i].id
										+ '\')" class="list-group-item">');
								html
										.push('<i class="fa '
												+ (array[i].isactive === '0' ? 'fa-frown-o'
														: 'fa-home')
												+ '"></i>&nbsp;'
												+ array[i].rolename);
								html
										.push('<div class="btn-group btn-group-xs" style="float: right">');
								html
										.push('<button type="button" class="btn btn-warning" onclick="editRole(\''
												+ array[i].id
												+ '\',\''
												+ array[i].rolename
												+ '\',\''
												+ array[i].isactive
												+ '\',\''
												+ array[i].roledesc
												+ '\')"><i class="fa fa-cog"></i></button>');
								html
										.push('&nbsp;<button type="button" class="btn btn-danger" onclick="delRole(\''
												+ array[i].id
												+ '\',\''
												+ array[i].rolename
												+ '\')"><i class="fa fa-trash-o"></i></button>');
								html.push('</div></a>');
							}
						}
						if (id && id === array[i].id) {
							j = i;
						}

						$("#sysRole").html(html.join(''));
						show(array[j].id, array[j].rolename, array[j].isactive,
								array[j].roledesc);
					}
				}
			});
}
function show(id) {
	this.roleid = id;
	$("#" + id).siblings().removeClass("active");
	$("#" + id).addClass("active");
	initUser();
	if ($('#roleTab li:first').hasClass("active")) {
		initMenu(id);
	}
}

function addRole() {
	var baseInfo = $("#baseInfo");
	baseInfo.find("input:not(:radio)").val('');
	baseInfo.find("input:radio[value='1']").attr("checked", "checked");
	baseInfo.find("#btnDel").hide();
	$("#baseInfo").modal('show');
}
function editRole(id, rolename, isactive, roledesc) {
	var baseInfo = $("#baseInfo");
	baseInfo.find("#id").val(id);
	baseInfo.find("#rolename").val(rolename);
	baseInfo.find("input:radio[value='" + isactive + "']").attr("checked",
			"checked");
	baseInfo.find("#roledesc").val(roledesc);
	baseInfo.find("#btnDel").show();
	$("#baseInfo").modal('show');
}
function saveRole() {
	App.ajax(_path + "/role/saveRole", $("#formBase").serialize(), function(
			data) {
		switch (data.statusCode) {
		case 200:
			App.bubble(data.statusCode, "保存成功！");
			initRole(data.id);
			$("#baseInfo").modal('hide');
			break;
		case 500:
			App.bubble(data.statusCode, data.msg);
			break;
		default:
			alert("操作失败！");
			break;
		}
	});
}
function delRole(id, rolename) {
	if (window.confirm("确认删除角色：" + rolename + "?")) {
		App.ajax(_path + "/role/delRole?id=" + roleid, '', function(data) {
			switch (data.statusCode) {
			case 200:
				App.bubble(data.statusCode, "删除成功！");
				initRole(data.id);
				$("#baseInfo").modal('hide');
				break;
			case 500:
				App.bubble(data.statusCode, data.msg);
				break;
			default:
				alert("操作失败！");
				break;
			}
		});
	}
	return false;
}

// ========================角色用户===========================
function initUser() {
	if (oTable) {
		oTable.fnPageChange('first');
		return;
	}
	oTable = $("#dataList")
			.DataTable(
					{
						"sAjaxSource" : _path + "/role/initUserRole",
						"fnServerParams" : function(aoData) {
							aoData.push({
								"name" : "id",
								"value" : roleid
							});
						},
						"sServerMethod" : "POST",
						"sAjaxDataProp" : "dataList",
						"aoColumns" : [
								{
									"sTitle" : "选择",
									"sWidth" : "5%",
									"mData" : function(obj) {
										return "<input type='checkbox' value='"
												+ obj.id + "'/>";
									}
								},
								{
									"sTitle" : "用户名",
									"mData" : "username",
									"sWidth" : "15%"
								},
								{
									"sTitle" : "组织单位",
									"mData" : "organ.organame",
									"sWidth" : "10%"
								},
								{
									"sTitle" : "状态",
									"mData" : "status",
									"sWidth" : "10%",
									"mRender" : function(data, type, full) {
										var status = '';
										switch (data) {
										case '01':
											status = "正常";
											break;
										case '02':
											status = "禁用";
											break;
										default:
											break;
										}
										return status;
									}
								},
								{
									"sTitle" : "手机",
									"mData" : "mobile",
									"sWidth" : "15%"
								},
								{
									"sTitle" : "操作",
									"sWidth" : "20%",
									"mData" : function(obj) {
										var html = new Array();
										html.push('<div style="width: 80px;">');
										html
												.push('<a href="javascript:delUser(\''
														+ obj.id
														+ '\',\''
														+ obj.username
														+ '\')" class="btn default btn-xs purple">');
										html
												.push('<i class="fa fa-edit"></i> 删除</a>');
										html.push('</div>');
										return html.join('');
									}
								} ]
					});
}
function initUsers() {
	if (bTable) {
		bTable.fnPageChange('first');
		return;
	}
	bTable = $("#addUserList")
			.DataTable(
					{
						"sAjaxSource" : _path + "/role/findUsers",
						"fnServerParams" : function(aoData) {
							aoData.push({
								"name" : "roleid",
								"value" : roleid
							});
						},
						"sServerMethod" : "POST",
						"sAjaxDataProp" : "dataList",
						"aoColumns" : [
								/*
								 * { "sTitle": "选择", "sWidth": "5%", "mData":
								 * function(obj) { return "<input
								 * type='checkbox' value='"+obj.id+"'/>"; } },
								 */
								{
									"sTitle" : "用户名",
									"mData" : "username",
									"sWidth" : "15%"
								},
								{
									"sTitle" : "组织单位",
									"mData" : "organ.organame",
									"sWidth" : "10%"
								},
								/*
								 * { "sTitle": "性别", "mData": "gender",
								 * "sWidth": "10%", "mRender": function ( data,
								 * type, full ) { var gender = ''; switch(data) {
								 * case '01': gender = "男"; break; case '02':
								 * gender = "女"; break; default: break; } return
								 * gender; }},
								 */
								{
									"sTitle" : "状态",
									"mData" : "status",
									"sWidth" : "10%",
									"mRender" : function(data, type, full) {
										var status = '';
										switch (data) {
										case '01':
											status = "正常";
											break;
										case '02':
											status = "禁用";
											break;
										case '03':
											status = "删除";
											break;
										case '04':
											status = "锁定";
											break;
										default:
											break;
										}
										return status;
									}
								},
								{
									"sTitle" : "移动电话",
									"mData" : "mobile",
									"sWidth" : "10%"
								},
								/*
								 * { "sTitle": "注册时间", "mData": "createTime",
								 * "sWidth": "10%" },
								 */
								{
									"sTitle" : "操作",
									"sWidth" : "20%",
									"mData" : function(obj) {
										var html = new Array();
										html.push('<div style="width: 80px;">');
										html
												.push('<a href="javascript:addUserToRole(\''
														+ obj.id
														+ '\')" class="btn default btn-xs purple">');
										html
												.push('<i class="fa fa-edit"></i> 添加</a>');
										html.push('</div>');
										return html.join('');
									}
								} ]
					});
}
function addUser() {
	initUsers();
	$('#modal_addUser').modal('show');
}
function addUserToRole(userids) {
	App.ajax(_path + "/role/addUserToRole", "roleid=" + this.roleid
			+ "&userids=" + userids, function(data) {
		switch (data.statusCode) {
		case 200:
			App.bubble(data.statusCode, "添加成功！");
			initUser();
			$('#modal_addUser').modal('hide');
			break;
		case 500:
			App.bubble(data.statusCode, "添加失败！");
			break;
		default:
			alert("操作失败！");
			break;
		}
	});
}
function delUser(userid, username) {
	if (userid && userid.length > 0
			&& window.confirm("确认删除用户" + username + "？")) {
		App.ajax(_path + "/role/delUserFromRole", "roleid=" + this.roleid
				+ "&userids=" + userid, function(data) {
			switch (data.statusCode) {
			case 200:
				App.bubble(data.statusCode, "删除成功！");
				initUser();
				break;
			case 500:
				App.bubble(data.statusCode, "删除失败！");
				break;
			default:
				alert("操作失败！");
				break;
			}
		});
	}
}
function delUsers() {
	var inputs = $("input:checked", $("#dataList"));
	if (inputs.length > 0) {
		if (window.confirm("确认删除用户所选用户？")) {
			var ids = new Array();
			for (var i = 0, len = inputs.length; i < len; i++) {
				ids.push(inputs[i].value);
			}
			userids = ids.join();
			App.ajax(_path + "/role/delUserFromRole", "roleid=" + this.roleid
					+ "&userids=" + userids, function(data) {
				switch (data.statusCode) {
				case 200:
					App.bubble(data.statusCode, "删除成功！");
					initUser();
					break;
				case 500:
					App.bubble(data.statusCode, "删除失败！");
					break;
				default:
					alert("操作失败！");
					break;
				}
			});
		}
	} else {
		alert("请选择要删除的记录！");
	}
}

// ========================菜单权限===========================
function initMenu(id) {
	if (menugrid) {
		checkMenu(id);
		return;
	}
	$
			.ajax({
				type : "post",
				url : _path + "/sysMenu/listSysMenu",
				success : function(data) {
					menugrid = $("#menugrid")
							.ligerGrid(
									{
										headerRowHeight : 36,
										rowHeight : 36,
										width : '99%',
										height : '89%',
										checkbox : false,
										alternatingRow : true,
										usePager : false,
										columns : [
												{
													display : '选择',
													name : '',
													width : '4%',
													render : function(row) {
														var html = '<input id="'
																+ row.pid
																+ '" type="checkbox" name="menuid" value="'
																+ row.id
																+ '" style="margin-top:5px" onclick="changeBox(\''
																+ row.pid
																+ '\',\''
																+ row.id
																+ '\')"/>';
														return html;
													}
												},
												{
													display : '菜单名称',
													name : 'menuname',
													width : '32%',
													align : 'left',
													render : function(row) {
														if (row.menuimg != "") {
															return "<i class='fa "
																	+ row.menuimg
																	+ "'></i>&nbsp;&nbsp;"
																	+ row.menuname;
														} else {
															return row.menuname;
														}
													}
												},
												{
													display : '上级菜单',
													name : 'pmenuName',
													width : '20%',
													align : 'center',
													editor : {
														type : 'text'
													}
												},
												{
													display : '状态',
													name : 'isactive',
													width : '10%',
													type : 'int',
													align : 'center',
													render : function(row) {
														if (row.isactive == "1") {
															return "<i class='fa fa-check'></i>";
														} else {
															return "<i class='fa fa-frown-o'></i>";
														}
													}
												}, {
													display : 'URL',
													name : 'url',
													width : '35%',
													align : 'left',
													editor : {
														type : 'text'
													}
												} ],
										data : data,
										tree : {
											columnName : 'menuname'
										},
										rownumbers : true
									});
					checkMenu(id);
				}
			});
}

function change(id) {
	if ($("#menugrid").find(":checkbox[value='" + id + "']").is(":checked")) {
		App.ajax(_path + "/sysMenu/addRoleMenu?roleid=" + this.roleid
				+ "&meunid=" + id);
	} else {
		App.ajax(_path + "/sysMenu/addRoleMenu?roleid=" + this.roleid
				+ "&meunid=" + id);
	}
}
function checkMenu(id) {
	var $Menu = $("#menugrid");
	$Menu.find(":checkbox").removeAttr("checked");
	App.ajax(_path + "/sysMenu/findRoleMenu?roleid=" + id, '', function(data) {
		if (data && data.roleMenu) {
			var roleMenu = data.roleMenu;
			for (var i = 0, len = roleMenu.length; i < len; i++) {
				$Menu.find(":checkbox[value='" + roleMenu[i] + "']").attr(
						"checked", "checked");
			}
		}
	});
}
function changeBox(pid, id) {
	if ($("#menugrid").find(":checkbox[value='" + id + "']").is(":checked")) {
		// 选中父菜单
		$("#menugrid").find(":checkbox[value='" + pid + "']").attr("checked",
				"checked");
		// 选中子菜单
		$("#menugrid").find(":checkbox[id='" + id + "']").attr("checked",
				"checked");
	} else {
		// 不选中父菜单
		var inputs = $("input[id='" + pid + "']:checked", $("#menugrid"));
		if (inputs.length == 0) {
			$("#menugrid").find(":checkbox[value='" + pid + "']").removeAttr(
					"checked");
		}
		// 不选中子菜单
		$("#menugrid").find(":checkbox[id='" + id + "']").removeAttr("checked");
	}
}
/**
 * @title : 保存
 */
function saveMenu() {
	var inputs = $("input[name='menuid']:checked", $("#menugrid"));
	if (inputs.length > 0) {
		var id = new Array();
		for (var i = 0, len = inputs.length; i < len; i++) {
			id.push(inputs[i].value);
		}
		App.ajax(_path + "/sysMenu/addRoleMenu", "roleid=" + this.roleid
				+ "&menuid=" + id.join(), function(data) {
			switch (data.statusCode) {
			case 200:
				App.bubble(data.statusCode, "保存成功！");
				break;
			case 500:
				App.bubble(data.statusCode, "保存失败！");
				break;
			default:
				alert("操作失败！");
				break;
			}
		});
	} else {
		App.bubble(500, "请至少选择一个菜单！");
	}
}

/**
 * @title :全选
 */
var _CHECKFLAG = true;
function onSelectAllClick() {
	$('input:checkbox[name="menuid"]').each(function() {
		this.checked = _CHECKFLAG;
	});
	_CHECKFLAG = !_CHECKFLAG;
}
